// 管理用户数据

import { ref } from 'vue'
import { defineStore } from "pinia";
import { loginAPI } from "@/apis/user.js";
import { useCartStore } from './cartStore.js'
import { mergeCartAPI } from "@/apis/cart.js";

export const useUserStore = defineStore('user', () => {
    const cartStore = useCartStore();
    // 1. 定义管理用户数据的 state
    const userInfo = ref({})

    // 2. 定义获取接口数据的action函数
    const getUserInfo = async ({account, password}) => {
        const response = await loginAPI({account, password})
        userInfo.value = response.result
        // 合并购物车
        await mergeCartAPI(cartStore.cartList.map(item => {
                return {
                    skuId: item.skuId,
                    count: item.count,
                    selected: item.selected
                }
            }
        ))
        cartStore.updateNewList();
    }
    // 退出是清除用户信息
    const clearUserInfo = () => {
        userInfo.value = {}
        cartStore.clearCart();
    }

    // 3. 以对象的格式把state 和  action  返回
    return {userInfo, getUserInfo, clearUserInfo}
}, {
    persist: true
})

